// 2025/6/3 create
package com.xsh.opensltest;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.xsh.opensltest.plugin.AarManifest;
import com.xsh.opensltest.plugin.XmlParser;
import com.xsh.opensltest.utils.FullException;

import java.io.File;
import java.io.InputStream;


public class FilePicker extends Activity
{
    private static int request_importPlugin = 1;
    private static String tag = FilePicker.class.getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, request_importPlugin);
        } else {
            Toast.makeText(this, "未找到文件管理器", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == request_importPlugin && resultCode == RESULT_OK && data != null)
        {
            Uri uri = data.getData();
            try{
                InputStream inputStream = getContentResolver().openInputStream(uri);
                File tempDir = new File(App.appCacheDir,"temp");
                if(!tempDir.exists())
                {
                    tempDir.mkdir();
                }
                File cacheAar = new File(App.appCacheDir,"temp/temp.aar");
                FileUtils.copyInputStreamToFile(inputStream, cacheAar);

                FileUtils fu = new FileUtils();
                fu.unzip(cacheAar,tempDir.getAbsolutePath());
                Toast.makeText(this,"文件解压完成",Toast.LENGTH_SHORT).show();
                if(new File(App.appCacheDir,"temp").exists())
                {
                    Log.d(tag,"文件解压完成:true");

                    File manifestFile = new File(App.appCacheDir,"temp/AndroidManifest.xml");
                    if (manifestFile.exists())
                    {
                        Log.d(tag,"检测配置文件,ui,lib");
                        Log.d(tag, "配置文件存在");
                        AarManifest aarManifest = XmlParser.parseManifest(manifestFile);
                        String pluginName = aarManifest.getPluginName();
                        String layout = "assets/ui.json";
                        String libName = aarManifest.getLibName();
                        Log.d(tag, "pluginName: " + pluginName);
                        //Log.d(tag,"layout: " + layout);
                        Log.d(tag, "libName:" + libName);
                        Log.d(tag, "开始导入ui");
                        FileUtils.copyFile(new File(App.appCacheDir,"temp/"+layout).getAbsolutePath(),new File(App.appFilesDir,pluginName + "/layout/ui.json").getAbsolutePath());
                        Log.d(tag,"开始导入配置文件");
                        FileUtils.copyFile(new File(App.appCacheDir,"temp/AndroidManifest.xml").getAbsolutePath(),new File(App.appFilesDir,pluginName+ "/config/AndroidManifest.xml").getAbsolutePath());
                        Log.d(tag, "开始导入classes.jar");
                        FileUtils.copyFile(new File(App.appCacheDir,"temp/assets/classesd8.jar").getAbsolutePath(),new File(App.appFilesDir, pluginName + "/java/" + "classesd8.jar").getAbsolutePath());
                        // 安装 lib
                        new File(App.appFilesDir, pluginName).mkdir();
                        Log.d(tag, "安装lib");
                        if(DeviceUtils.getBestAbi().equals("armabi-v7a"))
                        {
                            Log.d(tag,"copy arm_v7a lib");
                            FileUtils.copyFile(new File(App.appCacheDir,"temp/jni/armabi-v7a/"+libName).getAbsolutePath(),new File(App.appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("arm64-v8a"))
                        {
                            Log.d(tag,"copy arm_v8a lib");
                            FileUtils.copyFile(new File(App.appCacheDir,"temp/jni/arm64-v8a/"+libName).getAbsolutePath(),new File(App.appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("x86"))
                        {
                            Log.d(tag,"copy x86 lib");
                            FileUtils.copyFile(new File(App.appCacheDir,"temp/jni/x86/"+libName).getAbsolutePath(),new File(App.appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("x86_64"))
                        {
                            FileUtils.copyFile(new File(App.appCacheDir,"temp/jni/x86_64/"+libName).getAbsolutePath(),new File(App.appFilesDir,pluginName + "/lib" + "/" + libName).getAbsolutePath());
                            Log.d(tag,"copy x86_64 lib");
                        }

                        // 用于插件界面EventHandler
                        File dexDir = new File(App.appCacheDir,"dex" + File.separator + pluginName);
                        if(!dexDir.exists())
                        {
                            dexDir.mkdirs();
                        }
                        Log.d(tag,"dex目录：" + dexDir);
                        Log.d(tag,"插件导入完成");
                        finish();
                    }
                    else {
                        Log.d(tag,"AndroidManifest.xml not exists");
                        }
                }

            }catch (Exception e) {
                Toast.makeText(this, "读取文件失败", Toast.LENGTH_SHORT).show();
                FullException.print(e);
            }
        }
    }
}
